<template>
  <div>
    <el-dialog title="比例分摊" :visible.sync="dialogVisible" width="70%">
      <div>
        <div class="button">
          <el-button size="small" type="primary" @click="exporttab"
            >导 出</el-button>
        </div>
        <div>
            <el-table 
              :data="tableData" 
              border 
              style="width: 100%"
              max-height="400"
              :header-cell-style="{ 'background-color': '#fafafa' }"
              :span-method="objectSpanMethod"
            >
              <!-- 固定列：序号、部门、班组、班组编码、合计占比 -->
              <el-table-column prop="index" label="序号" align="center" width="80"></el-table-column>
              <el-table-column prop="department" label="部门" align="center" width="150"></el-table-column>
              <el-table-column prop="teamName" label="班组" align="center" width="150"></el-table-column>
              <el-table-column prop="teamCode" label="班组编码" align="center"></el-table-column>
              <el-table-column prop="totalRatio" label="合计占比" align="center"></el-table-column>
              <!-- 动态列：根据deviceType数组生成设备类型列 -->
              <el-table-column 
                v-for="(type, idx) in deviceTypes" 
                :key="idx" 
                :label="type" 
                align="center"
              >
                <!-- 用作用域插槽获取当前行数据，根据索引取对应设备的占比 -->
                <template slot-scope="scope">
                  {{ scope.row.deviceRatios[idx] }}%
                </template>
              </el-table-column>
            </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small"  @click="dialogVisible = false"
          >取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getPowerReportapi,getRatioReportapi} from '@/api/energy-consumption/demand/record-report'
import TableColumn from '@/components/Table/index.vue'
import { exportexcel } from '@/utils/excel'
export default {
  name: 'CallPoliceGetDialod',
  components: {
    TableColumn
  },
  data() {
    return {
      dialogVisible: false,
      tableData: [],
      deviceTypes: [],
      // 用于存储部门列的合并信息
      departmentMerge: [],
      // 用于存储第一行（总占比行）的合并信息
      firstRowMerge: [],
      rowval: {}
    }
  },

  mounted() {},

  methods: {
    async tosplit(row){
      this.rowval={...row}
      this.dialogVisible=true
      const {data:{entity}}=await getRatioReportapi(row.id)
      this.deviceTypes = entity.deviceType; // 保存设备类型列表
      this.formatTableData(entity)
    },
    formatTableData(entity) {
      const tempData = [];
      let index = 1;
      // 1. 处理总占比行（放在最上方）
      tempData.push({
        index: index++, // 总占比行无序号
        department: entity.totalRatio.teamName, // 总占比行无部门
        teamName: entity.totalRatio.teamName,
        teamCode: entity.totalRatio.teamName,
        totalRatio:entity.totalRatio.teamName ,
        deviceRatios: entity.totalRatio.deviceRatioList // 设备占比数组（与deviceType对应）
      })
      // 2. 处理各部门的班组数据
      Object.entries(entity.departmentList).forEach(([deptName, teams]) => {
        teams.forEach(team => {
          tempData.push({
            index: index++, // 序号自增
            department: deptName,
            teamName: team.teamName,
            teamCode: team.teamCode,
            totalRatio: team.ratio +'%',
            deviceRatios: team.deviceRatioList // 设备占比数组（与deviceType对应）
          });
        });
      });
      this.tableData = tempData;
      this.calculateMergeData()
    },
    // 计算需要合并的单元格信息
    calculateMergeData() {
      // 重置合并信息
      this.departmentMerge = []
      this.firstRowMerge = []
      
      if (!this.tableData.length) return
      
      // 1. 处理第一行合并（所有列都合并第一行相同的数据）
      const firstRowValue = this.tableData[0].teamName
      let firstRowCount = 0
      
      this.tableData.forEach((row, index) => {
        if (row.teamName === firstRowValue) {
          firstRowCount++
        }
        this.firstRowMerge.push(firstRowCount)
      })
      
      // 2. 处理部门列（第二列）的合并
      let currentDept = ''
      let deptCount = 0
      
      this.tableData.forEach(row => {
        if (row.department !== currentDept) {
          currentDept = row.department
          deptCount = 1
        } else {
          deptCount++
        }
        this.departmentMerge.push(deptCount)
      })
    },
    // 合并单元格的核心方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 处理第一行相同数据的合并（所有列）
      if (rowIndex === 0) {
        // 确定需要合并的列
        const columnsToMerge = [1,2,3,4]
        // 如果当前列是需要合并的列
        if (columnsToMerge.includes(columnIndex)) {
          // 第一个需要合并的列负责展示，其他列隐藏
          return columnIndex === columnsToMerge[0]
            ? { rowspan: 1, colspan: columnsToMerge.length } // 合并列数
            : { rowspan: 0, colspan: 0 }; // 隐藏其他列
        }
      }
      // 处理部门列（第二列，columnIndex=1）的合并
      if (columnIndex === 1) {
        const mergeCount = this.departmentMerge[rowIndex]
        if (mergeCount === 1) {
          // 找到当前部门的总条数
          const currentDept = row.department
          const total = this.tableData.filter(item => item.department === currentDept).length
          return {
            rowspan: total,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
      // 其他情况不合并
      return {
        rowspan: 1,
        colspan: 1
      }
    },
    exporttab() {
      exportexcel('/ecm-microservice-biz/ecm/annual/apportion/ratio/report/exportExcel',{id:this.rowval.id},'比例分摊表')
    }
  }
}
</script>
<style lang="scss" scoped>
.button{
  margin-bottom: 10px;
}
::v-deep .el-dialog__footer{
  display: none;
}
</style>
